/**
 * Created by kenkozheng on 2014/8/20.
 */

var MenuScene = cc.Scene.extend({
    _hero:null,
    _playBtn:null,
    _aboutBtn:null,

    ctor:function () {
        this._super();
        var layer = new cc.Layer();
        this.addChild(layer);
        this._websocketluoji();
        shoudaoshuju=false;
        var winSize = cc.director.getWinSize();
        var bgWelcome = new cc.Sprite("res/graphics/bgWelcome.jpg");
        bgWelcome.x = winSize.width/2;
        bgWelcome.y = winSize.height/2;
        layer.addChild(bgWelcome);

        var title = new cc.Sprite("#welcome_title.png");
        title.x = 800;
        title.y = 555;
        layer.addChild(title);

        this._hero = new cc.Sprite("#welcome_hero.png");
        this._hero.x = -this._hero.width/2;
        this._hero.y = 400;
        layer.addChild(this._hero);

        var move = cc.moveTo(2, cc.p(this._hero.width/2 + 100, this._hero.y)).easing(cc.easeOut(2));
        this._hero.runAction(move);


        var play_nike=new cc.LabelTTF('NewMiracle', "Arial", 30);
        play_nike.x = this._hero.getPositionX;
        play_nike.y = this._hero.getPositionY+100;
        this._hero.addChild(play_nike,9);


        this._playBtn = new cc.MenuItemImage("#welcome_playButton.png", "#welcome_playButton.png", this._play);
        this._playBtn.x = 700;
        this._playBtn.y = 350;

        this._aboutBtn = new cc.MenuItemImage("#welcome_aboutButton.png", "#welcome_aboutButton.png", this._about, this);
        this._aboutBtn.x = 500;
        this._aboutBtn.y = 250;

        if(cc.sys.isNative)
            var soundButton = new cc.MenuItemToggle(new cc.MenuItemImage("#soundOn0002.png"), new cc.MenuItemImage("#soundOff.png"), Sound.toggleOnOff);
        else
            var soundButton = new SoundButton();
        soundButton.x = 45;
        soundButton.y = winSize.height - 45;
        var menu = new cc.Menu(this._playBtn, this._aboutBtn, soundButton);  //默认都居中叠在一起
        layer.addChild(menu);
        menu.x = menu.y = 0;    //如果不设置menu位置，则自动屏幕居中。

        Sound.playMenuBgMusic();
        this.scheduleUpdate();

        cc.eventManager.addListener({
            event: cc.EventListener.KEYBOARD,
            onKeyReleased: function(keyCode, event) {
                if (keyCode == cc.KEY.back) {
                    cc.director.end();
                }
            }}, this);

        return true;
    },
    _websocketluoji:function(){

        var that=this;
        if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
        var client_list={},timeid, reconnect=false;
        ws = new WebSocket("ws://121.40.85.96:7272");
        ws.onopen = function() {
          console.log('链接成功');
            timeid && window.clearInterval(timeid);
            if(!name)
            {
                that._prompt();
            }
            if(!name) {
                return ws.close();
            }
            if(reconnect == false)
            {
                console.log(name);
                var namesplit=name.split('&');
                nike=namesplit[0];
                var room_id=namesplit[1];
                var login_data = JSON.stringify({"type":"login","client_name":nike,"room_id":room_id});
                ws.send(login_data);
                ws.send(JSON.stringify({"type":"getownid"}));
                reconnect = true;
             }
            else
            {
                // 断线重连
                var login_data = JSON.stringify({"type":"login","client_name":nike,"room_id":room_id});
                ws.send(login_data);
    	    }

        }
        ws.onmessage = function(e) {

            var data = JSON.parse(e.data);
            console.log(data);
            switch(data['type']){
                // 服务端ping客户端(检测是否突然断线)
                   case 'ping':
                    ws.send(JSON.stringify({"type":"pong"}));
                    break;

                case 'getownid':
                    own_client=data['ownid'];
                    break;

                   case 'login':
                     that.flush_client_list(data['client_list']);

                     if(data['iszhuji']=='true')
                     {

                         that._playBtn.visible=true;

                     }
                     else
                     {

                         that._playBtn.visible=false;
                         var waite=new cc.LabelTTF('等到主机开始.....', "Arial", 30);
                         waite.x = 700;
                         waite.y = 350;
                         that.addChild(waite);
                     }
                     console.log(data['client_name']+"登录成功");
                    break;
                //获取服务器发过来得昵称和玩家id
                case 'startgame':
                   console.log('开始游戏');
                    console.log('所有客户端昵称和id');

                    console.log(data['allclient']);
                    cc.director.runScene(new GameScene(data['allclient']));
                    break;
                case 'position':

              console.log('收到坐标');
                    shoudaoshuju=true;
                   positionXY=data['positionXY'];
                    break;



            }
        }
        ws.onclose = function() {

        }
        ws.onerror = function() {
            console.log("出现错误");
        };

    },
    _prompt:function (){
        name = prompt('昵称&输入房间：(newmiracle&1221', '');
        if(!name){
            alert('输入为空，请重新输入！');
            this._prompt();
        }
     },
    flush_client_list:function(client_list)
    {

        for(var p in client_list){
            var nickname;
            if(p==0)
            {
                nickname=new cc.LabelTTF('我是主机'+client_list[p]['client_name'], "Arial", 30);
                nickname.setColor(cc.color(255,0,0));
            }
            else
            {
                nickname=new cc.LabelTTF('玩家'+p+client_list[p]['client_name'], "Arial", 30);
            }

            nickname.x = 100;
            nickname.y = 300+p*40;

            this.addChild(nickname);
        }

    },
   _play:function() {
        Sound.playCoffee();

       var start_game = JSON.stringify({"type":"startgame"});
       ws.send(start_game);

    },

    _about:function() {
      alert('正在完善');
    },

    update:function(dt) {
        var currentDate = new Date();
        this._hero.y = 400 + (Math.cos(currentDate.getTime() * 0.002)) * 25;
        this._playBtn.y = 350 + (Math.cos(currentDate.getTime() * 0.002)) * 10;
        this._aboutBtn.y = 250 + (Math.cos(currentDate.getTime() * 0.002)) * 10;
    }

});
